package sf.view.fields;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JLabel;
import javax.swing.JTextField;

import sf.model.fields.DecimalFieldModel;
import sf.model.fields.AbstractFieldModel;
import sf.model.fields.event.FieldChangeEvent;

public class DecimalField extends AbstractField
{

	private static final long serialVersionUID = -2806527197113137251L;

	private class DecimalFieldController implements ActionListener,
			FocusListener
	{

		
		public void actionPerformed(ActionEvent e)
		{
			updateField();
		}

		
		public void focusGained(FocusEvent e)
		{
			// TODO Auto-generated method stub

		}

		
		public void focusLost(FocusEvent e)
		{
			updateField();
		}

		private void updateField()
		{
			if (((DecimalFieldModel) getModel()).check(inputField.getText())
					&& !inputField.getText().equals(getModel().getValue()))
			{
				getModel().setValue(inputField.getText());
			}
		}

	}

	private JTextField inputField;
	private DecimalFieldModel model;
	private DecimalFieldController controller;

	public DecimalField()
	{
		model = new DecimalFieldModel();
		controller = new DecimalFieldController();

		JLabel label = new JLabel(getLabelText());
		add(label, BorderLayout.WEST);

		inputField = new JTextField();
		inputField.addActionListener(controller);
		inputField.addFocusListener(controller);
		add(inputField, BorderLayout.EAST);

		model.addChangeListener(this);
	}

	
	public AbstractFieldModel getModel()
	{
		return model;
	}

	
	public Object getValue()
	{
		return model.getValue();
	}

	
	public void setModel(AbstractFieldModel model)
	{
		this.model = (DecimalFieldModel) model;
		this.model.addChangeListener(this);
		inputField.setText((String) this.model.getValue());
	}

	
	public void setValue(Object value)
	{
		model.setValue(value);
	}

	
	public void changePerformed(FieldChangeEvent event)
	{
		inputField.setText((String) model.getValue());
	}

	
	public void setEditable(boolean editable)
	{
		// TODO Auto-generated method stub

	}

}
